<template>
  <el-dialog
    :title="!dataForm.brandId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="cancel"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="200px"
    >
      <el-form-item label="品牌名" prop="name">
        <el-input v-model="dataForm.name" placeholder="品牌名"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo地址" prop="logo">
        <!-- <el-input v-model="dataForm.logo" placeholder="品牌logo地址"></el-input> -->
        <el-upload
          class="upload-demo"
          action="https://gulimail-hello-czq.oss-cn-beijing.aliyuncs.com/"
          :before-upload="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :before-remove="beforeRemove"
          multiple
          :data="policy"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="介绍" prop="descript">
        <el-input v-model="dataForm.descript" placeholder="介绍"></el-input>
      </el-form-item>
      <el-form-item label="显示状态" prop="showStatus">
        <!-- <el-input v-model="dataForm.showStatus" placeholder="显示状态[0-不显示；1-显示]"></el-input> -->
        <el-switch
          v-model="dataForm.showStatus"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="0"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="检索首字母" prop="firstLetter">
        <el-input
          v-model="dataForm.firstLetter"
          placeholder="检索首字母"
        ></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {update} from 'lodash'

export default {
  data () {
    return {
      policy: {},
      fileList: [],
      visible: false,
      dataForm: {
        brandId: 0,
        name: '',
        logo: '',
        descript: '',
        showStatus: '',
        firstLetter: '',
        sort: '',
      },
      dataRule: {
        name: [{required: true, message: '品牌名不能为空', trigger: 'blur'}],
        logo: [
          {required: true, message: '品牌logo地址不能为空', trigger: 'blur'},
        ],
        descript: [
          {required: true, message: '介绍不能为空', trigger: 'blur'},
        ],
        showStatus: [
          {
            required: true,
            message: '显示状态[0-不显示；1-显示]不能为空',
            trigger: 'blur',
          },
        ],
        firstLetter: [
          {validator: this.firstLetterValidate, trigger: 'blur'},
        ],
        sort: [
          {validator: this.sortValidate, trigger: 'blur'},
        ],
      },
    }
  },
  methods: {
    // 自定义校验首字母
    firstLetterValidate (rule, value, callback) {
      const letterRegex = /^[a-zA-Z]$/ // 只允许单个英文字母
      if (!value) {
        callback(new Error('检索首字母不能为空'))
      } else if (!letterRegex.test(value)) {
        callback(new Error('检索首字母必须是一个字母'))
      } else {
        callback() // 校验通过
      }
    },

    // 自定义校验排序
    sortValidate (rule, value, callback) {
      const sortRegex = /^[0-9]+$/ // 只允许正整数
      if (value === '') {
        callback(new Error('排序不能为空'))
      } else if (!sortRegex.test(value)) {
        callback(new Error('排序必须是非负整数'))
      } else {
        callback() // 校验通过
      }
    },
    init (id) {
      this.dataForm.brandId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.brandId) {
          this.$http({
            url: this.$http.adornUrl(
              `/gulimailproduct/brand/info/${this.dataForm.brandId}`
            ),
            method: 'get',
            params: this.$http.adornParams(),
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.brand.name
              this.dataForm.logo = data.brand.logo
              this.dataForm.descript = data.brand.descript
              this.dataForm.showStatus = data.brand.showStatus
              this.dataForm.firstLetter = data.brand.firstLetter
              this.dataForm.sort = data.brand.sort
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          // 校验通过后提交表单数据
          console.log('表单提交数据:', this.dataForm)
          // 提交表单逻辑
          if (!this.dataForm.brandId) {
            this.insert()
          } else {
            this.update()
          }
        } else {
          console.log('表单校验失败')
          return false
        }
      })
    },
    insert () {
      this.fileList = []
      let brand = {
        name: this.dataForm.name,
        logo: this.dataForm.logo,
        descript: this.dataForm.descript,
        showStatus: this.dataForm.showStatus,
        firstLetter: this.dataForm.firstLetter,
        sort: this.dataForm.sort,
      }
      console.log(brand)
      this.$http({
        url: this.$http.adornUrl('/gulimailproduct/brand/save'),
        method: 'post',
        data: this.$http.adornData(brand, false),
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '新增成功',
            type: 'success',
            duration: 1500,
          })
          this.$emit('refreshDataList')
          this.visible = false
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    update () {
      this.fileList = []
      let brand = {
        brandId: this.dataForm.brandId,
        name: this.dataForm.name,
        logo: this.dataForm.logo,
        descript: this.dataForm.descript,
        showStatus: this.dataForm.showStatus,
        firstLetter: this.dataForm.firstLetter,
        sort: this.dataForm.sort,
      }
      console.log(brand)
      this.$http({
        url: this.$http.adornUrl('/gulimailproduct/brand/update'),
        method: 'post',
        data: this.$http.adornData(brand, false),
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '修改成功',
            type: 'success',
            duration: 1500,
          })
          this.$emit('refreshDataList')
          this.visible = false
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
      console.log(this.dataForm.logo)
      // this.deletePicture(this.dataForm.logo);
    },
    handlePreview (file) {
      console.log('Preview triggered for:', file)

      // 返回一个 Promise
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl('/thirdparty/oss/policy'),
          method: 'get',
        })
          .then(({data}) => {
            if (data) {
              this.policy = {
                OSSAccessKeyId: data.accessid,
                success_action_status: 200,
                policy: data.policy,
                Signature: data.signature,
                key: data.dir + file.name,
              }
              console.log('Policy retrieved successfully:', this.policy)
              this.dataForm.logo = data.host + '/' + data.dir + file.name
              resolve() // 通知调用者，policy 已填充完成
            } else {
              console.error('Failed to retrieve policy:', data)
              reject(new Error('Failed to retrieve policy'))
            }
          })
          .catch((error) => {
            console.error('Error fetching policy:', error)
            reject(error) // 通知调用者发生错误
          })
      })
    },

    handleSuccess () {
      this.policy = {}
      console.log(this.fileList)
      console.log(this.policy)
    },
    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    cancel () {
      let url = this.dataForm.logo
      // this.deletePicture(url);
      this.visible = false
      this.fileList = []
    },
    deletePicture (url) {
      // 发送删除请求到后端
      this.$http({
        url: this.$http.adornUrl('/thirdparty/oss/delete'), // 请求的后端接口
        method: 'post', // 请求方式为 POST
        data: {url: url}, // 发送数据，包括文件 URL
      })
        .then((response) => {
          // 请求成功的回调
          console.log('File deleted successfully', response)
        })
        .catch((error) => {
          // 请求失败的���调
          console.error('Error deleting file', error)
        })
    },
  },
}
</script>
